/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.base.service;

import java.util.List;
import java.util.Set;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.chlitina.store.common.service.BaseService;
import com.chlitina.store.modules.base.dao.CustomerEmployeeRelationshipDao;
import com.chlitina.store.modules.base.entity.CustomerEmployeeRelationship;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * 客户员工关系Service
 * @author lvbo
 * @version 2013-09-30
 */
@Component
@Transactional(readOnly = true)
public class CustomerEmployeeRelationshipService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(CustomerEmployeeRelationshipService.class);
	
	@Autowired
	private CustomerEmployeeRelationshipDao customerEmployeeRelationshipDao;
	
	public CustomerEmployeeRelationship get(Long id) {
		return customerEmployeeRelationshipDao.findOne(id);
	}
	
	@Transactional(readOnly = false)
	public List<CustomerEmployeeRelationship> findByCustomer(Long cid) {
		DetachedCriteria dc = customerEmployeeRelationshipDao.createDetachedCriteria();
		if (cid != null) {
			dc.add(Restrictions.eq("customer.id", cid));
		}
		List<CustomerEmployeeRelationship> list = customerEmployeeRelationshipDao.find(dc);
		Set<CustomerEmployeeRelationship> set = Sets.newHashSet();
		set.addAll(list);
		List<CustomerEmployeeRelationship> newList = Lists.newArrayList();
		for (CustomerEmployeeRelationship ce : set) {
			newList.add(ce);
		}
		return newList;
	}
	@Transactional(readOnly = false)
	public List<CustomerEmployeeRelationship> findByEmployee(Long eid) {
		DetachedCriteria dc = customerEmployeeRelationshipDao.createDetachedCriteria();
		if (eid !=null) {
			dc.add(Restrictions.eq("employee.id", eid));
		}
		return customerEmployeeRelationshipDao.find(dc);
	}
	@Transactional(readOnly = false)
	public int delete(Long cid, Long eid) {
		int sum = 0;
		DetachedCriteria dc = customerEmployeeRelationshipDao.createDetachedCriteria();
		if (cid != null) {
			dc.add(Restrictions.eq("customer.id", cid));
		}
		if (eid != null) {
			dc.add(Restrictions.eq("employee.id", eid));
		}
		List<CustomerEmployeeRelationship> find = customerEmployeeRelationshipDao.find(dc);
		for (CustomerEmployeeRelationship cer : find) {
			customerEmployeeRelationshipDao.delete(cer);
			sum ++;
		}
		return sum;
	}
	@Transactional(readOnly = false)
	public void save(CustomerEmployeeRelationship customerEmployeeRelationship) {
		customerEmployeeRelationshipDao.clear();
		customerEmployeeRelationshipDao.save(customerEmployeeRelationship);
	}
	
}
